use strict;
use HTML::TreeBuilder;
use File::Path;
use Time::Local 'timelocal';
#use warnings;
use File::Spec::Functions;
use Cwd;
my $currentdir = "C:\\E2E_Monitoring\\C6_MAPS_SR6\\report";

my ($secs,$min,$hr,$dy,$mth,$yr,$wd,$yd,$ds)=localtime();

#Mark case status 0: fail   1:pass   2:skipped
my $haspositioning = 2;
my $haspositioningnet = 2;
my $hassearchingpoi = 2;
my $hassearchingcategory = 2;
my $hasrouting = 2;
my $haswalking = 2;
my $hassyncshare = 2;
my $hasmorefolder = 2;
my $haspiao = 2;

#get epoch seconds 30 min ago
my ($secs,$min,$hr,$dy,$mth,$yr,$wd,$yd,$ds)=localtime();
my $epoch_seconds_now = timelocal( $secs,$min,$hr,$dy,$mth,$yr );
my $epoch_seconds_15min_ago = $epoch_seconds_now - 30*60;

#The lastest test result folder name
my $targetentryname;

#The dir of test result
my $workdir = 'C:\\E2E_Monitoring\\C6_MAPS_SR6\\logs\\';#maybe change the directory


#An array to mark 10 latest test result get from log.txt
my @log;

#To mark case's alert level
my %alertLevel =(
					positioning => "",
					positioningnet => "",
					searchingpoi => "",
					searchingcategory => "",
					routing => "",
					walking => "",
					syncshare => "",
					morefolder => "",
					piao => ""
                 );

#Get dir of latest test result 
sub gethtmlfile15minago
{
	#read the directory which save some directories, data(some html files) in it, save the entry in dircontent	
	opendir(DIR, $workdir) or die "can't open the directory! please try again";
	my @dircontent = readdir DIR;
	closedir DIR;
	my $dircount = @dircontent;
	my $entryname;
	my $found = 0;

	for ( my $i = 0; $i < $dircount; $i++ )
	{
		$entryname = @dircontent[$i];
		if ( $entryname eq ".." || $entryname eq "." )
		{
			next;
		}
		#get epoch second of current dir name
		my $dirnameyear = substr( $entryname, 18, 4 );
		my $dirnamemonth = substr( $entryname, 15, 2 );
		my $dirnameday = substr( $entryname, 12, 2 );
		my $dirnamehour = substr( $entryname, 23, 2 );
		my $dirnamemin = substr( $entryname, 26, 2 );
		my $dirnamesec = substr( $entryname, 29, 2 );
		$dirnameyear -= 1900;
		$dirnamemonth -= 1;
		my $epoch_seconds_dir = timelocal( $dirnamesec, $dirnamemin, $dirnamehour, $dirnameday, $dirnamemonth, $dirnameyear );
		
		if ( $epoch_seconds_dir >= $epoch_seconds_15min_ago )
		{
			$found = 1;
			$targetentryname = $entryname;
			$epoch_seconds_15min_ago = $epoch_seconds_dir;
			print "$targetentryname\n";		
		}	
	}
	
	if($found == 0)
	{
		my $sendalert = $currentdir.'\send_alert_email.py Alarm ResultNotFound';
		system($sendalert);
	}
}

#Get case status of case from html file
sub getDatafromhtml
{
	my $htmldir = $workdir."\\".$targetentryname."\\html\\testcases\\";
	$htmldir =~ s/\\\\/\\/g;
	opendir(DIR, $htmldir) or die "can't open the directory! please try again";
	my @htmlfiles = readdir DIR;
	closedir DIR;

	
	# read every html file
	my $filename;
	my $fileextname = ".html";
	for ( my $i = 0; $i < @htmlfiles; $i++ )
	{
		$filename = @htmlfiles[$i];
		# if it is html file
		if ( rindex( $filename, $fileextname ) != -1  )
		{
			my $righfilename = $htmldir.$filename;
			my $htmlroot = HTML::TreeBuilder->new;
			$htmlroot->parse_file( $righfilename );
			$htmlroot->eof();
			
			# get the start time information. It will be good to get the info if the html file content can be changed.
			foreach my $row( $htmlroot->find_by_tag_name( "td" ) )
			{
				foreach my $element( $row->content_list ) 
				{ 
					if ( $element =~ /Timer with id 'TimeMyPositionDefault' was found./ )
					{
						$haspositioning = 1;
						next;
					}
					elsif ( $element =~ /Failed to load my position using Default within 120s/ )
					{
						$haspositioning = 0;
						$alertLevel{positioning} = "P3";
						next;
					}
					elsif ( $element =~ /Timer with id 'TimeMyPositionNetwork' was found./ )
					{
						$haspositioningnet = 1;
						next;
					}
					elsif ( $element =~ /Failed to load my position using Network within 120s/ )
					{
						$haspositioningnet = 0;
						$alertLevel{positioningnet} = "P3";
						next;
					}
					elsif ( $element =~ /Timer with id 'TimeSearchRujia' was found./ )
					{
						$hassearchingpoi = 1;
						next;
					}
					elsif ( $element =~ /Failed to search Rujia hotel within 60s/ )
					{
						$hassearchingpoi = 0;
						$alertLevel{searchingpoi} = "P3";
						next;
					}
					elsif ( $element =~ /Timer with id 'TimeSearchCategory' was found./ )
					{
						$hassearchingcategory = 1;
						next;
					}
					elsif ( $element =~ /Failed to search Restaurant category within 60s/ )
					{
						$hassearchingcategory = 0;
						$alertLevel{searchingcategory} = "P3";
						next;
					}
					elsif ( $element =~ /Timer with id 'TimeDrive' was found./ )
					{
						$hasrouting = 1;
						next;
					}
					elsif ( $element =~ /Failed to calculate Drive routing within 180s/ )
					{
						$hasrouting = 0;
						$alertLevel{routing} = "P3";
						next;
					}
					elsif ( $element =~ /Timer with id 'TimeWalk' was found./ )
					{
						$haswalking = 1;
						next;
					}
					elsif ( $element =~ /Failed to calculate Walk routing within 180s/ )
					{
						$haswalking = 0;
						$alertLevel{walking} = "P3";
						next;
					}
					elsif ( $element =~ /Timer with id 'TimeSync' was found./ )
					{
						$hassyncshare = 1;
						next;
					}
					elsif ( $element =~ /Failed to Sync within 100s/ )
					{
						$hassyncshare = 0;
						$alertLevel{syncshare} = "P3";
						next;
					}
					elsif ( $element =~ /Timer with id 'TimeMore' was found./ )
					{
						$hasmorefolder = 1;
						next;
					}
					elsif ( $element =~ /Failed to open More page within 60s/ )
					{
						$hasmorefolder = 0;
						$alertLevel{morefolder} = "P3";
						next;
					}
					elsif ( $element =~ /Timer with id 'TimePiao' was found./ )
					{
						$haspiao = 1;
						next;
					}
					elsif ( $element =~ /Failed to search concert information within 60s/ )
					{
						$haspiao = 0;
						$alertLevel{piao} = "P3";
						next;
					}
				}
			}			
			
			$htmlroot = $htmlroot->delete;
		}
	}			
	
}

#Write current log to log.txt and delete the first log in log.txt
sub writeinfotolog
{
	my $logdir = $currentdir."\\log_SR6.txt";
	
	if (-e $logdir) {
		print "File exists.\n";
		open LOG, $logdir or die "Couldn't open $logdir for writing: $!";
		@log = <LOG>;
    }else{
		print "Create log.txt.\n";
		open LOG, ">", $logdir or die "Couldn't open $logdir for writing: $!";
		for(my $i = 0; $i <= 9; $i++)
		{
		    $log[$i] = "111111111\n";
		}
		print LOG @log;
	}
	
	close(LOG);
	
	for(my $i = 0; $i <= 9; $i++)
	{
		$log[$i] = $log[$i+1];
	}
	
	$log[9] = $haspositioning.$haspositioningnet.$hassearchingpoi.$hassearchingcategory.
				$hasrouting.$haswalking.$hassyncshare.$hasmorefolder.$haspiao."\n";
	print @log;
	open LOG, ">", $logdir or die "Couldn't open $logdir for writing: $!";
	print LOG @log;
	close(LOG);

}


#judge alert level from log and send alert out
sub checkalertLevel
{
	while ((my $key, my $value) = each %alertLevel)
	{
		print "$key\n";
		my $num;
		if($value eq "P3"){
			if($key eq "positioning")
			{
				$num = readLogfromarray(0);
				#print "num: $num\n";
				sendAlert($key, $num);
				next;
			}
			elsif ($key eq "positioningnet")
			{
				$num = readLogfromarray(1);
				sendAlert($key, $num);
				next;
			}
			elsif ($key eq "searchingpoi")
			{
				$num = readLogfromarray(2);
				sendAlert($key, $num);
				next;
			}
			elsif ($key eq "searchingcategory")
			{
				$num = readLogfromarray(3);
				sendAlert($key, $num);
				next;
			}
			elsif ($key eq "routing")
			{
				$num = readLogfromarray(4);
				sendAlert($key, $num);
				next;
			}
			elsif ($key eq "walking")
			{
				$num = readLogfromarray(5);
				sendAlert($key, $num);
				next;
			}
			elsif ($key eq "syncshare")
			{
				$num = readLogfromarray(6);
				sendAlert($key, $num);
				next;
			}
			elsif ($key eq "morefolder")
			{
				$num = readLogfromarray(7);
				sendAlert($key, $num);
				next;
			}
			elsif ($key eq "piao")
			{
				$num = readLogfromarray(8);
				sendAlert($key, $num);
				next;
			}	
		}
		next;		
	}
}


#Get the faile num of a case in the last 10 test assert, $j is case number
sub readLogfromarray
{
	my($j) = @_;
	my $num = 0;
	
	for (my $i = 0; $i < 10; $i++)
	{
		if(substr(@log[$i], $j, 1) eq "0")
		{
			$num += 1;
		}
	}
	print "fail num: $num\n";
	return $num;
	
}

#Send email alert
#$key is case name, $num is fail num of the case in the last 10 test assert.
sub sendAlert
{
	my($key, $num) = @_;
	my $currentlevel;
	if($num == 1)
	{
		$currentlevel = "P3";
	}
	elsif($num > 1 && $num < 4)
	{
		$currentlevel = "P2";
	}
	elsif($num >= 4)
	{
		$currentlevel = "P1";
	}
	
	my $sendalert = $currentdir.'\send_alert_email.py '.$key.' '.$currentlevel;
	system($sendalert);
}

#Check status of test assert
sub checkTestAssert
{
	my $assertLevel;
	if(substr(@log[9], 6, 1) eq "2")
	{
		$assertLevel = "P3";
		if(substr(@log[8], 6, 1) eq "2")
		{
			$assertLevel = "P2";
			if(substr(@log[7], 6, 1) eq "2")
			{
				$assertLevel = "P1";
			}
		}
		my $sendalert = $currentdir.'\send_alert_email.py assertfailed '.$assertLevel;
		system($sendalert);
		return;
	}
	
	print "No need to send assert alert";

}

gethtmlfile15minago;
getDatafromhtml;
writeinfotolog;
checkalertLevel;
checkTestAssert;







  
